define(function(require, exports, module) {
	'use strict';
    var rk = require('./rk');

    $.datepicker.setDefaults({
        yearRange: 'c-90:c+10'//全局，年份选择跨度100年，前90后10
    });

    /***
    对jquery原生方法的扩展
    ***/
    $.fn.jQhtml = $.fn.html; //缓存jquery的html()方法
    $.fn.extend({
        beBusy: function() {
            var me = $(this);

        },
        getScrollTop: function(){
            var elem = $(this);
            if(elem.isScroll()){
                var top = elem.find('.mCSB_container:first').css('top');
                top = parseInt(top);
                top = Math.abs(top);
                return top;
            }else{
                return elem.scrollTop();
            } 
        },
        beScrollTo: function(pos){
            var elem = $(this);
            if(elem.isScroll()){
                if(typeof pos == 'string'){
                    if(pos == 'bottom') pos = elem.find('.mCSB_container:first').height() + 500;
                    if(pos == 'top') pos = 0;
                }
                elem.mCustomScrollbar("scrollTo", pos, {
                    scrollInertia: 0
                });
            }else{
                elem.scrollTop(pos);
            }
            return elem;
        },
        unScroll: function(force){
            var elem = $(this);
            if(typeof force == 'undefined')force = false;
            try{
                if(force)elem.data('mCS', null).removeData('mCS');//解决malihu的bug，其data关键字mCS在多次重复初始化时未清空，导致初始化的if未进入。 
                elem.mCustomScrollbar("destroy");
                elem.removeClass('mCS_destroyed');
                elem.removeClass('mCustomScrollbar');
                //注意：此处是为了修正malihu当前的一个bug：当调用destroy时，会将所有滚动条都destroy掉,
                //      换言之，$(selector).mCustomScrollbar("destroy");的selector并不管用，因此重新调用bescroll将不应destroy的滚动条还原。
                $('.mCS_destroyed').beScroll();
            }catch(e){
                
            }
            return elem;
        },
        beScroll: function(opt) {
            if(typeof opt == 'undefined')opt = {};
            var elem = $(this);
            if (elem.isScroll()) {
                //elem.unScroll();
                return elem;
            }
            if(!opt.axis)opt.axis = 'y';
            var scrollOption = {
                theme: (opt.theme ? opt.theme : 'dark-3'),
                scrollInertia:(opt.scrollInertia ? opt.scrollInertia : 100),
                snapOffset: 0,
                axis: opt.axis,
                scrollbarPosition: (opt.scrollbarPosition ? opt.scrollbarPosition : 'outside'),
                autoHideScrollbar: (opt.autoHideScrollbar !== undefined ? opt.autoHideScrollbar : true),
                onTotalScrollOffset: (opt.onTotalScrollOffset !== undefined ? opt.onTotalScrollOffset : null),
                alwaysTriggerOffsets: (opt.alwaysTriggerOffsets !== undefined ? opt.alwaysTriggerOffsets : null),
                //autoExpandScrollbar:false,
                advanced:{
                    //autoExpandHorizontalScroll: (opt.axis.indexOf("x") >= 0 ? true : false),
                    //默认autoScrollOnFocus中含textarea，但这里把它去掉了，因为会引起scrollbar的大幅跳动
                    // autoScrollOnFocus: "input,select,button,datalist,keygen,a[tabindex],area,object,[contenteditable='true']" 
                },
                mouseWheel:{ 
                    scrollAmount: (rk.isMac ? 3 : 100)
                    //normalizeDelta: false,
                    //scrollButtons: 'stepped',
                    //deltaFactor: 15 //距离,DEBUG
                },
                callbacks: {
                    onTotalScroll: function(){  if(opt.onTotalScroll)(opt.onTotalScroll)(); },
                    //滚动中：
                    whileScrolling: function(){ 
                        var diff = new Date() - window.malihu_scroll_start; 
                        if(diff > 100){
                            $(elem).find(':focus').blur();
                            elem.find('select').each(function(i, el){
                                try{
                                    // $(el).selectmenu('close');
                                    // $(el).multiselect('close');
                                }catch(e){}
                            });
                            $('.ui-multiselect.ui-state-active').click();
                        }
                        if(opt.whileScrolling)(opt.whileScrolling)(); 
                    },
                    //滚动结束：
                    onScroll: function(){
                        delete window.malihu_scroll_start;
                        if(opt.onScroll)(opt.onScroll)(); 
                    },
                    //滚动开始：
                    onScrollStart:function(){
                        window.malihu_scroll_start = new Date();
                        if(opt.onScrollStart)(opt.onScrollStart)();
                    }
                }
            };
            if(rk.isMac){
                //针对苹果进行专门优化
                delete scrollOption.scrollInertia;
                delete scrollOption.mouseWheel.deltaFactor;
                // delete scrollOption.mouseWheel.scrollAmount;
                // console.debug(scrollOption) ;
            }
            elem.mCustomScrollbar(scrollOption);
            if($.isNumeric(opt.zindex)){
                elem.find('[id$="scrollbar_vertical"]').css('z-index', opt.zindex);
            }
            return elem;
        },
        isScroll: function() {
            var elem = $(this);
            return elem.hasClass('mCustomScrollbar') && elem.children('[id^="mCSB_"][class~="mCustomScrollBox"]').size() > 0;
        },
        updateScroll: function(top) {
            var elem = $(this);
            if(typeof top == 'undefined')top = false;//默认滚动条不重新回到顶部
            elem.mCustomScrollbar('update');
            if(top)
            elem.mCustomScrollbar('scrollTo', 'top', {
                scrollInertia: 0
            });
            return elem;
        },
        _getScrollOffset: function(){
            var elem = $(this);
            if(elem.isScroll()){
                var con = elem.find('.mCSB_draggerContainer');
                return con.innerHeight() - con.find('.mCSB_dragger:first').height();
            }
            return 0;
        },
        html: function(html, force) { //重写html，以支持虚拟滚动条
            var elem = $(this);
            var contentEl = elem;
            var usingPlugin = elem.isScroll();
            if(typeof force == 'undefined') force = false;/*强制冲掉滚动条，beLoading会用到*/
            if (usingPlugin) {
                contentEl = force ? elem.removeClass('mCustomScrollbar') : elem.find('> .mCustomScrollBox > .mCSB_container');
            }
            if (typeof html == 'undefined') {
                //get
                return contentEl.jQhtml.apply(contentEl, arguments);
            } else {
                // html = html + '';
                // //set
                // template.config('escape', false); //默认输出html的dom
                // var tpl = html;
                // var complier = template.render(tpl);
                // var html = complier({});
                // //contentEl.jQhtml.call(html);
                contentEl.jQhtml.apply(contentEl, arguments);
            }
            if (usingPlugin) {
                elem.updateScroll();
            }
            return elem;
        },
        beLoading: function(act){
            var elem = $(this);
            var className = elem.attr('class');
            var tagName = elem.prop('tagName');
            if(typeof act == 'undefined')act = null;
            if(!tagName)return;
            tagName = tagName.toLowerCase();
            if(act && act.fixedPosition){
                elem._beCoverLoading(act);
                return;
            }
            if(tagName == 'a' && (className && className.indexOf('pg-btn') >= 0)){
                elem._beBtnLoading(act);
            }else{
                elem.html('<span is="still-loading" style="display:none;"></span>');//, true/*force update*/);
                var delay = 1000;
                if(act && $.isNumeric(act.delay))delay = act.delay;
                window.clearTimeout(beloading_timer)
                beloading_timer = window.setTimeout(function(){
                    elem._beConLoading(act);
                }, delay);
            }            
            return elem;
        },
        _beCoverLoading: function(act){
            var __adjustCoverLoading = function(randomId){
                var offset = elem.offset();
                var loadingDiv = $('#'+randomId);
                loadingDiv.css({
                    position: 'fixed',
                    width: elem.outerWidth(),
                    height: elem.outerHeight(),
                    top: offset.top,
                    left: offset.left,
                    zIndex: 21
                });
                var top = (elem.height() - 80) * (1 - 0.618);
                top = top * (1 - 0.618);
                loadingDiv.find('.f_circle').css('top', top >= 0 ? top : 10);
            };

            var elem = $(this);
            
            if(elem.data('iscoverloading'))return;
            elem.data('iscoverloading', true);

            elem.uniqueId();
            var elemId = elem.attr('id');
            var randomId = elemId+'_loading';
            var tpl = require('../page/tmpl/tpl_loading_large.tpl');
            var html = rk.templateText(tpl, {label: ''});
            $('body').append('<div id="'+randomId+'" class="rk_cover_loading">'+html+'</div>');
            __adjustCoverLoading(randomId);
            if(!rk._loadinginfo)rk._loadinginfo = {};

            var co_lo_timer = window.setInterval(function(){//杀马特风味:P
                __adjustCoverLoading(randomId);
            }, 1);
            rk._loadinginfo['info'+elemId] = {
                menuId: randomId,
                timer: co_lo_timer
            };
        },
        _beConLoading: function(act){
            if(typeof act == 'undefined' || !act)act = {};
            if(!act.size)act.size = 'default';
            var elem = $(this);
            //是普通div或span
            if(elem.find('span[is="still-loading"]').size() == 0)return;//由于延时了200ms，如果用户的数据在200ms以内回来了，继续显示会冲掉。
            if(act.size == 'default'){
                elem.html( '<div class="pg-loading"><div class="ico">' + (act.label ? act.label : rk.lang('LOADING')) + '</div></div>' );
            }
            if(act.size == 'large'){
                var html = require('../page/tmpl/tpl_loading_large.tpl');
                elem.html( rk.templateText(html, {
                    label: (act.label ? act.label : rk.lang('LOADING'))
                }) );
            }
            if(act.round || act.noSpace){
                elem.find('.pg-loading').css('margin', 0);
                elem.find('.pg-loading .ico').css('margin', 0);
            }
            if($.isFunction(act.onShow)){
                (act.onShow)();
            }
        },
        _beBtnLoading: function(act){
            var elem = $(this);
            //是button
            if(act == 'delay'){
                elem.unLoading();
                elem.loading().loading('delay');
                return;
            }else if(act == 'end'){
                elem.unLoading();
                elem.loading().loading('end');
                return;
            }else{
                var text = elem.html();
                elem.loading({
                    ghostDisplayed: function (e, ghostId){
                        var ghost = $('#'+ghostId);
                        ghost.removeClass('disabled').addClass('pg-btn-disabled').html(text + '<div class="pg-btn-dots"></div>');
                        window.setInterval(function (){
                            var num = 19;
                            var dots = elem.attr('dots');
                            if(!dots)dots = '';
                            dots = dots + '.';
                            if(dots == '....')dots = '';
                            var div = ghost.find('.pg-btn-dots');
                            div.html(dots);
                            div.css('right', (num - div.outerWidth())+'px');//点向右弹出
                            elem.attr('dots', dots);
                            elem.attr('ghostId', ghostId);
                        }, 300);
                    }
                }).data('rkbtn', true); 
            }
        },
        unLoading: function(){
            window.clearTimeout(beloading_timer);
            var elem = $(this);
            var className = elem.attr('class');
            var elemId = elem.attr('id');

            elem.removeData('iscoverloading');
            if(rk._loadinginfo && rk._loadinginfo['info'+elemId]){
                var info = rk._loadinginfo['info'+elemId];
                var menuId = info.menuId;
                $('#'+menuId).off().remove();
                elem.removeData('rk_loading_id');
                window.clearInterval(info.timer);
                return;
            }
            var tagName = elem.prop('tagName').toLowerCase();
            if(tagName == 'a' && (className && className.indexOf('pg-btn') >= 0)){
                //是button
                if(elem.data('rkbtn')){
                    elem.loading('end');
                }
            }else{
                //是普通div或span
                elem.find('.pg-loading').remove();
            }
        },
        beTip: function(opt){
            var elem = $(this);
            if(elem.data('hasqtip')) {
                elem.attr('oldtitle', '');
                elem.qtip('destroy');
            }
            if(typeof opt == 'undefined'){
                opt = {}
            }
            if(typeof opt.closeDelay == 'undefined') opt.closeDelay = 1600;
            var conf = {
                position: {my: 'left center', at: 'right center'}, 
                style:{
                    classes: 'qtip-dark-rk'
                },
                hide: {
                    fixed: true,
                    delay: window._rk_never_hide_tip ? 9999999999 : 50
                },
                events: {
                    show: function(event, api) {
                        if(elem.data('shouldclosetip')){
                            var tipid = elem.data('shouldclosetip');
                            $('#qtip-' + tipid).remove();
                            elem.qtip('hide');
                            elem.removeData('shouldclosetip');
                        }
                        if(!opt.hideFix) {
                            window.clearTimeout(api.closeTimer);
                            if (opt.closeDelay !== false)
                                api.closeTimer = window.setTimeout(function () {
                                    elem.qtip('hide');
                                }, opt.closeDelay);
                        }
                    }
                }
            };
            if(opt.title)elem.attr('title', opt.title);
            if(opt.dir == 'right') conf.position = {my: 'left center', at: 'right center'};
            if(opt.dir == 'left') conf.position = {my: 'right center', at: 'left center'};
            if(opt.dir == 'bottom') conf.position = {my: 'top center', at: 'bottom center'};
            if(opt.dir == 'top') conf.position = {my: 'bottom center', at: 'top center'};
            elem.qtip(conf);
            return elem;
        },
        unTip: function(){
            var elem = $(this);
            if(elem.data('hasqtip')) {
                var tipid = elem.data('hasqtip');
                elem.qtip('hide');
                elem.data('shouldclosetip', tipid);
                elem.qtip('destroy');
            }
        }
    });
    var beloading_timer;
});
